package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.PurchaseRefundChooseGoodsAdapter;
import com.example.sunmiv1.base.BaseChooseActivity;
import com.example.sunmiv1.entity.ClassificationBean;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

// 採購管理.新增採購退單.選擇商品
public class PurchaseRefundChooseGoodsActivity extends BaseChooseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.view_bg_top)
    View viewBgTop;
    @BindView(R.id.tv_pick_sort)
    TextView tvPickSort;
    @BindView(R.id.ed_num_search)
    EditText edNumSearch;
    @BindView(R.id.iv_search_code)
    ImageView ivSearchCode;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.view_bg_footer)
    View viewBgFooter;
    @BindView(R.id.btn_checkall)
    Button btnCheckall;
    @BindView(R.id.btn_add_to_list)
    Button btnAddToList;
    @BindView(R.id.rv_goods_choose)
    RecyclerView rvGoodsChoose;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.btn_checkall_not)
    Button btnCheckallNot;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;


    private PurchaseRefundChooseGoodsAdapter adapter;
    private List<GoodsStoreRetreatInfo.DataBean> dataList;
    private GoodsStoreRetreatInfo goodsStoreRetreatInfo;
    private ArrayList<GoodsStoreRetreatInfo.DataBean> choiceList; // 回傳參數列表

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_CATEGORY_INFO:
                    break;
                case GET_GOODS_STORE_RETREAT_INFO:
                    progressBar.setVisibility(View.GONE);
                    setAdapter();
                    break;
                case GET_OTHER_GOODS_STORE_RETREAT_INFO:
                    setAdapter();
                    break;
                case GET_ERROR_STATUS:
                    break;
            }
        }
    };

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.title_title, R.id.tv_pick_sort, R.id.iv_search_code, R.id.iv_search, R.id.btn_checkall, R.id.btn_checkall_not, R.id.btn_add_to_list, R.id.btn_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                putExtra(this, PurchaseRefundAddingActivity.class, choiceList,"");
                break;
            case R.id.iv_search_code:  // 調起掃碼
                startQrCode();
                break;
            case R.id.iv_search:
                LogUtil.i("searchText:" + edNumSearch.getText().toString().trim());
                getListInfo(1);
                break;
            case R.id.btn_checkall:  // 全選操作
                btnCheckall.setVisibility(View.GONE);
                btnCheckallNot.setVisibility(View.VISIBLE);
                adapter.checkAll();
                break;
            case R.id.btn_checkall_not: // 全不選操作
                adapter.checkAllNot();
                btnCheckallNot.setVisibility(View.GONE);
                btnCheckall.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_add_to_list:  //添加到上頁列表中
                addToListAndRemove();
                break;
            case R.id.btn_ok:  //添加到上頁列表並返回
                addToList();
                putExtra(this, PurchaseRefundAddingActivity.class, choiceList,"");
                break;
            case R.id.tv_pick_sort:  //分類篩選
                if (classificationBean != null && classificationBean.getStatus() == 1 && classificationBean.getGoodscate().size() > 0) {
                    showPickerView();
//                    showPickerView(options1Items,options2Items,options3Items,classificationBean);
                } else {
                    Toast.makeText(this, "無法獲取分類列表", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_to_top:
                rvGoodsChoose.smoothScrollToPosition(0);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
    }

    @Override
    protected void initChoiceList() {
        dataList = new ArrayList<>();  // 顯示信息列表
        choiceList = new ArrayList<>();// 已選擇列表
    }

    @Override
    protected void getListInfo(int page) {
        getGoodsInfo(page);
    }

    /* 添加到回傳列表中，並且移除當前頁面*/
    protected void addToListAndRemove() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                notInIdArr.add(dataList.get(i).getId());
                adapter.notifyItemRemoved(i);
                choiceList.add(dataList.remove(i));
            }
        }
    }

    /* 直接添加到回傳列表*/
    protected void addToList() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                choiceList.add(dataList.remove(i));
            }
        }
    }

    @Override
    protected void setAdapter() {
        if (adapter == null) {
//            dataList = new ArrayList<>();  // 顯示信息列表
            adapter = new PurchaseRefundChooseGoodsAdapter(dataList, this);
            rvGoodsChoose.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }

    }


    @Override
    protected void initListener() {
        adapter.setCBListener((isChecked, position) -> {
            dataList.get(position).setChecked(isChecked);
            if (choiceList.size() == dataList.size()) {
                btnCheckall.setVisibility(View.GONE);
                btnCheckallNot.setVisibility(View.VISIBLE);
//                LogUtil.i(R.string.purRefundAdding_check_all);
            }
        });
    }

    /* 監聽手機系統返回鍵*/
    @Override
    public void onBackPressed() {
        putExtra(this, PurchaseRefundAddingActivity.class, choiceList, "");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }


    @Override
    public void getInfo(String tvShowText) {
        tvPickSort.setText(tvShowText);
        getListInfo(1);
    }

    /**
     * 獲取可選擇商品列表
     */
    private void getGoodsInfo(int page) {
        loadingDialog.show();
        String url;
        if ("1".equals(userType)) {
            url = Common.GOODS_STORE_RETREAT_1;
        } else {
            url = Common.GOODS_STORE_RETREAT_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("supplier_id", supplierId);
            jsonObject.put("warehouse_id", warehouseId);
            jsonObject.put("notInIds", toNotInIds(notInIdArr)); // 已選中的貨物id（選中傳回上頁，可從上頁跳轉到此頁的時候返回此id）
            jsonObject.put("searchText", edNumSearch.getText().toString().trim());
            jsonObject.put("page", page);
            jsonObject.put("limit", limit);
            jsonObject.put("person1", category[0]);
            jsonObject.put("person2", category[1]);
            jsonObject.put("person3", category[2]);
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                goodsStoreRetreatInfo = GsonUtils.JsonToBean(text, GoodsStoreRetreatInfo.class);
                if (goodsStoreRetreatInfo.getStatus() == 1) {
                    if (page == 1) {
                        dataList.clear();
                    }
                    dataList.addAll(goodsStoreRetreatInfo.getData());
                    LogUtil.i("dataList:" + dataList.size());
                    if (dataList.isEmpty()) {
                        Toast.makeText(PurchaseRefundChooseGoodsActivity.this, "未找到對應貨物", Toast.LENGTH_SHORT).show();
                    }
                    loadingDialog.dismiss();
                    mHandler.sendEmptyMessage(GET_GOODS_STORE_RETREAT_INFO);
                    if (dataList.size() == 4) {
                        getOtherGoodsInfo();
                    }
                } else {// status
                    loadingDialog.dismiss();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    /*加載剩下的商品信息*/
    private void getOtherGoodsInfo() {
        String url = "";
        if (userType.equals("1")) {
            url = Common.GOODS_STORE_RETREAT_1;
        } else if (userType.equals("2")) {
            url = Common.GOODS_STORE_RETREAT_2;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("supplier_id", supplierId);
            jsonObject.put("warehouse_id", warehouseId);
            jsonObject.put("notInIds", toNotInIds(notInIdArr)); // 已選中的貨物id（選中傳回上頁，可從上頁跳轉到此頁的時候返回此id）
            jsonObject.put("searchText", edNumSearch.getText().toString().trim());
            jsonObject.put("person1", category[0]);
            jsonObject.put("person2", category[1]);
            jsonObject.put("person3", category[2]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                goodsStoreRetreatInfo = GsonUtils.JsonToBean(text, GoodsStoreRetreatInfo.class);
                if (goodsStoreRetreatInfo.getStatus() == 1) {
                    dataList.addAll(goodsStoreRetreatInfo.getData().subList(4, goodsStoreRetreatInfo.getData().size()));
                    LogUtil.i("dataList(2):" + dataList.size());
                    mHandler.sendEmptyMessage(GET_OTHER_GOODS_STORE_RETREAT_INFO);
                } else {// status
//                    Toast.makeText(PurchaseRefundAddingActivity.class,"數據走丟了~",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

}
